#include "widget.h"
#include "ui_widget.h"
#include "chatdialog.h"
#include <QPushButton>
#include <QLineEdit>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    resize(500, 220);

    m_chatA = nullptr;
    m_chatB = nullptr;

    if (auto btn = this->findChild<QPushButton*>("startButton")) {
        connect(btn, &QPushButton::clicked, this, &Widget::onStartChat);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onStartChat()
{
    const auto editA = this->findChild<QLineEdit*>("lineEditA");
    const auto editB = this->findChild<QLineEdit*>("lineEditB");
    const QString nameA = editA ? editA->text().trimmed() : QString();
    const QString nameB = editB ? editB->text().trimmed() : QString();

    if (nameA.isEmpty() || nameB.isEmpty()) {
        return;
    }

    if (m_chatA) { m_chatA->close(); delete m_chatA; m_chatA = nullptr; }
    if (m_chatB) { m_chatB->close(); delete m_chatB; m_chatB = nullptr; }

    m_chatA = new ChatDialog(nameA, this);
    m_chatB = new ChatDialog(nameB, this);

    m_chatA->setPeer(m_chatB);
    m_chatB->setPeer(m_chatA);

    m_chatA->show();
    m_chatB->show();
}

